package com.liaogui.consumer.shiro;

import com.liaogui.common.entity.userinfo.UserInfoEntity;
import com.liaogui.common.service.userinfo.UserInfoService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

/**
 * 自定义Realm
 */
@Component
public class CustomerRealm extends AuthorizingRealm {
    @Reference
    protected UserInfoService userInfoService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权start");
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证start");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String userName = usernamePasswordToken.getUsername();
        UserInfoEntity userInfoEntity = userInfoService.selectUserInfo(userName);
        if (null == userInfoEntity){
            return null;//抛出异常
        }
        return new SimpleAuthenticationInfo(userName,userInfoEntity.getPassword(),userInfoEntity.getPhone());
    }
}
